<?php
/**
 * Created by PhpStorm.
 * User: dong
 * Date: 2016/10/26
 * Time: 18:09
 */

namespace app\components\behaviors;


use yii\base\Behavior;
use yii\base\ErrorException;
use yii\db\ActiveRecord;

class DatetimeBehavior extends Behavior
{
    public $createDate;
    public $updateDate;
    public function events()
    {
        return [
           ActiveRecord::EVENT_BEFORE_INSERT => 'setValue',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'setValue',

        ];
    }
    public function  setValue(){

        //判断是添加还是修改
        $model = $this->owner;
        /**@var $model ActiveRecord*/
        if ($model->isNewRecord) {
            //如果新增对model的创建日期属性和修改日期属性赋值
            $this->_setValue([$this->createDate,$this->updateDate]);
        } else {
            //否则对修改日期属性赋值
            $this->_setValue($this->updateDate);
        }

    }

    protected function _setValue($attributes)
    {
        //获取当前时间
        $date = date('Y:m:d H:i:s',time());
        //如果参数不是数组,转换成数组格式
        if (!is_array($attributes)) $attributes = [$attributes];
        //循环数组
        $model = $this->owner;
        /**@var $model ActiveRecord*/
        foreach ($attributes as $attribute) {
            if (!$attribute ){
                continue;
            }
            if ($model->hasAttribute($attribute)) {
                //对Model的属性赋值
                $model->$attribute = $date;
            } else {
                throw new ErrorException('属性值不存在! 请检查是不是输错了,亲!');
            }

        }

    }

}